package org.ediba.siri.core.publication.data;

import java.util.Collection;
import java.util.Map;

import org.ediba.siri.core.Filter;
import org.ediba.siri.core.common.data.HibernateDomainDao;
import org.ediba.siri.core.publication.domain.PublicationCountry;
import org.hibernate.Criteria;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

public class HibernatePublicationCountryDao extends HibernateDomainDao<PublicationCountry, Integer> implements PublicationCountryDao {

	public HibernatePublicationCountryDao() {super(PublicationCountry.class);}

	@Override
	protected DetachedCriteria buildCriteria(Map<Filter, Collection<Object>> filters) {
		DetachedCriteria detachedCriteria = this.buildCriteria();
		Disjunction or;
		Conjunction and = Restrictions.conjunction();
		
		for (Map.Entry<Filter,Collection<Object>> filter : filters.entrySet()){
			or = Restrictions.disjunction();
			for (Object value : filter.getValue())
				switch (filter.getKey()) {
				case ID:
					or.add(Restrictions.idEq((Integer)value));
				break;
				case PUBLICATIONCOUNTRY_MESSAGE:
					or.add(Restrictions.ilike(Filter.PUBLICATIONCOUNTRY_MESSAGE.getProperty(),(String)value,MatchMode.ANYWHERE));
				break;
				}
			and.add(or);
		}
		detachedCriteria.add(and);
		detachedCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		return detachedCriteria;
	}
}
